package com.guanglan.shiro;

import com.guanglan.entity.SysPermission;
import com.guanglan.entity.SysRole;
import com.guanglan.entity.SysUser;
import com.guanglan.service.ShiroService;
import com.guanglan.service.SysUserService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.util.ByteSource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import java.util.ArrayList;
import java.util.List;

/**
 * Created with IntelliJ IDEA.
 * 作者: 光蓝Comet
 * Date: 2018-06-22 10:50
 * Description: 一句话说明这个类的作用
 * Since 1.0
 */
@Component
public class WebShiroRealm extends AuthorizingRealm {

    private static final Logger logger = LoggerFactory.getLogger(WebShiroRealm.class);

    @Autowired
    private ShiroService shiroService;
    @Autowired
    private SysUserService sysUserService;

    /**
     * 授权操作
     * @param principal
     * @return
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principal) {
        //当前登陆用户名
        String userName = (String)principal.getPrimaryPrincipal();
        logger.info("开始授权操作，当前登陆用户【{}】",userName);
        //获取当前登陆用户所对应的角色
        List<SysRole> roles = shiroService.selectSysRolesByUserName(userName);
        List<String> roleList = new ArrayList<>();
        if(roles != null && roles.size() > 0){
            for(SysRole role : roles){
                roleList.add(role.getRoleName());
            }
        }

        //获取当前登陆用户所对应的权限
        List<SysPermission> perms = shiroService.selectSysPermissionByUserName(userName);
        List<String> permissionList = new ArrayList<>();
        if(perms != null && perms.size() > 0){
            for(SysPermission permissions : perms){
                permissionList.add(permissions.getPermission());
            }
        }
        SimpleAuthorizationInfo simpleAuthorInfo = new SimpleAuthorizationInfo();
        //进行角色授权
        simpleAuthorInfo.addRoles(roleList);
        //进行权限菜单授权
        simpleAuthorInfo.addStringPermissions(permissionList);
        return simpleAuthorInfo;
    }

    /**
     * 认证操作
     * @param authenticationToken
     * @return
     * @throws AuthenticationException
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        UsernamePasswordToken token=(UsernamePasswordToken) authenticationToken;
        //获取当前登陆用户名
        String userName = token.getUsername();
        logger.info("开始认证操作，当前登陆用户【{}】",userName);
        //通过用户名获取当前用户信息
        SysUser user = sysUserService.selectSysUserByUserName(userName);
        //获取用户密码
        Object credentials = user.getPassWord();
        //获取盐值
        ByteSource salt = ByteSource.Util.bytes(String.valueOf(user.getSalt()));
        //进行认证操作
        SimpleAuthenticationInfo authenticationInfo = new SimpleAuthenticationInfo(user.getUserName(),credentials,salt,getName());
        //将当前用户存入session
        this.setSession("currentUser", userName);
        return authenticationInfo;
    }

    /**
     * 将当前用户存入Session
     * @param key
     * @param value
     */
    private void setSession(Object key, Object value){
        Subject currentUser = SecurityUtils.getSubject();
        if(null != currentUser){
            Session session = currentUser.getSession();
            if(null != session){
                logger.info("将当前用户存入Session");
                session.setAttribute(key, value);
            }
        }
    }
}
